<template>
  <div style="width:400px;" id="out">
    <span>用户名：{{userInfo.username}}</span>
    <el-divider></el-divider>
    <span>性别：{{userInfo.sex}}</span>
    <el-divider></el-divider>
    <span>年龄：{{userInfo.age}}</span>
    <el-divider></el-divider>
    <el-upload id="p1" class="upload"
               :action="uploadUrl"
               :show-file-list="false"
               :before-upload="beforeUpload"
               :on-success="afterUpload"
               :auto-upload="true"
               :data="userInfo">
      <!-- <el-image v-if="imageUrl" :src="imageUrl" class="avatar" fit="fit"></el-image> -->
      <i  class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>

    <!-- <div>
        <el-button @click="showImg">显示</el-button>
        <el-button @click="delImg">删除</el-button>
    </div> -->

  </div>
</template>

<script>
export default {
  data() {
    return {
      test: true,
      avatarPath: this.$uploadPath+"/user/getAvatar?username="+this.$store.state.username,
      userInfo: {username: '', sex: '', age: 0, avatar: ''},
      uploadUrl: this.$uploadPath + "/user/uploadAvatar",
      imageUrl: '',
      imageTypes: ["image/jpg","image/jpeg","image/png","image/pjpeg","image/gif","image/bmp","image/x-png"]
    };
  },
  methods: {
    // 获取个人信息
    getUserInfo: function(username) {
      this.$http("/user/getUserInfo", {
        params: { username: this.$store.state.username }
      })
      .then(response => {
        this.userInfo = response.data;
      })
      .catch(err => err);
    },
    // 头像上传之前的函数，参数为上传的文件对象
    beforeUpload: function(file) {
      // 判断上传的文件的大小，格式是否符合规范
      if (this.imageTypes.indexOf(file.type) == -1) {
        this.$message({
          message: "请检查上传图片格式的文件",
          type: "error"
        });
        return false;
      } else if (file.size / 1024 / 1024 > 2) {
        this.$message({
          message: "文件大于2M，请压缩",
          type: "error"
        });
        return false;
      } else {
      }
    },
    afterUpload: function(response, file) {
      this.$message({message: response.message, type: "success"});
      this.imageUrl = URL.createObjectURL(file.raw);
      this.delImg();
      this.showImg();
    },
    showImg() {
      var p1 = document.getElementById("p1");
      var s1 = document.createElement("img")
      p1.appendChild(s1)
      s1.setAttribute("src", this.avatarPath+"&rand="+Math.random())
      s1.setAttribute("id", "img1")
      s1.style.width="100px"
      s1.style.height="100px"
    },
    delImg() {
      var s1 = document.getElementById("img1")
      var p1 = document.getElementById("p1");
      p1.removeChild(s1)
    }

  },
  mounted() {
    this.getUserInfo();
    this.showImg();
  }
};
</script>

<style>
.upload{
  display: inline;
}
.avatar {
  width:100px;
  height:100px;
}
.avatar-uploader-icon {
  text-align: center;
  width: 95px;
  height: 95px;
  font-size:30px;
  color: black;
  line-height: 100px;
}
input[type=file] {
  display: none
}
</style>
